package ex.recruit.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import modules.recruit.entity.Town;
import modules.recruit.form.TownForm;
import modules.recruit.service.TownService;
import modules.system.entity.Attach;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.RequestUtils;

import site.user.form.RegionImageFormSite;

import com.guinea.core.service.EntityService;
import com.guinea.core.utils.CommonUtils;
import com.guinea.core.utils.StringUtils;
import com.guinea.core.web.StrutsSimpleAction;

import ex.recruit.form.TownImportForm;
import ex.recruit.service.TownServiceEx;
import ex.system.service.AttachServiceEx;

public class TownImportAction extends StrutsSimpleAction {
	private String errorMessages;
	TownServiceEx townServiceEx;
	AttachServiceEx attachServiceEx;
	private FormFile formFile;
	

	public EntityService getEntityService() {
		return townServiceEx;
	}


	public TownServiceEx getTownServiceEx() {
		return townServiceEx;
	}


	public void setTownServiceEx(TownServiceEx townServiceEx) {
		this.townServiceEx = townServiceEx;
	}


	public AttachServiceEx getAttachServiceEx() {
		return attachServiceEx;
	}



	public void setAttachServiceEx(AttachServiceEx attachServiceEx) {
		this.attachServiceEx = attachServiceEx;
	}



	protected String saveWrapper(String text) {
		return "<script>window.parent.successImport('" + text
				+ "')</script>";
	}

	protected void initProperties() {
		super.initProperties();
		errorMessages = "";
		formFile = null;
	}
	
	public ActionForward ajaxSaveValidator(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		TownImportForm townImportForm = (TownImportForm) form;
		formFile = townImportForm.getFile();
		if (!validateFile(formFile))
			return handleFile(mapping, request, response);
		return null;
	}
	
	protected boolean validateFile(FormFile file) {
		if (file == null || file.getFileSize() < 1
				|| file.getFileSize() > 2 * 1024 * 1024) {
			errorMessages += "请上传一个大小不超过2M的EXCEL文档";
			return valid = false;
		}
		return true;
	}

	/**
	 * 保存对象的Action函数.
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public ActionForward ajaxSave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		//上传文件
		Long attachId = getAttachServiceEx().saveFile(formFile,"/town-import");
		Attach attach = getAttachServiceEx().getAttach(attachId);
		String physicalPath = System.getProperty("app.path")+ attach.getWebPath();
		File file = new File(physicalPath);
		if(!file.exists() || file.isDirectory()){
			errorMessages += "文件丢失";
			renderHtml(response,
					saveWrapper("{\"error\":\"" + errorMessages + "\"}"));
			return null;
		}
		//解析文件
		TownImportForm townImportForm = (TownImportForm) form;
		ActionMapping stepMapping = new ActionMapping();
		ServletContext servletContext = request.getSession().getServletContext();
		List provinces = (List) servletContext.getAttribute("provinces");
		List cities = (List) servletContext.getAttribute("cities");
		List districts = (List) servletContext.getAttribute("districts");
		int startRowNum = 2;
		HSSFWorkbook workbook = null;
		try {
			workbook = new HSSFWorkbook(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(workbook == null){
			errorMessages += "文件解析失败";
			renderHtml(response,
					saveWrapper("{\"error\":\"" + errorMessages + "\"}"));
			return null;
		}
		
		HSSFSheet sheet = workbook.getSheetAt(0);
		List successObjs = new ArrayList();
		for(int r=startRowNum; r < sheet.getPhysicalNumberOfRows(); r++) {
			HSSFRow row = sheet.getRow(r);
			TownForm townForm = getTownForm(row, provinces, cities, districts);
			//空行结束
			if(townForm == null) break;
			
			townForm.setServlet(townImportForm.getServlet());
			stepMapping.setName("townForm");
			if(!validateForm(stepMapping, townForm, request)){
				MessageResources messageResources = getResources(request);
				Locale userLocale = RequestUtils.getUserLocale(request, null);
				String result = "{\"error\":[";
				result += "\"第 "+(r+1)+" 行校验出错：\",";
				for (Iterator iter = formErrors.get(); iter.hasNext();) {
					ActionMessage m = (ActionMessage) iter.next();
					String message = messageResources.getMessage(userLocale,m.getKey(),m.getValues());
					if(StringUtils.isEmpty(message)) continue;
					result += "\"" + message + "\"";
					if (iter.hasNext())
						result += ",";
				}
				result += "]}";
				renderHtml(response,
						saveWrapper(result));
				return null;
			}
			successObjs.add(townForm);
		}
		//保存
		getTownServiceEx().saveTownForms(successObjs);
		
		renderHtml(response,
				saveWrapper("{\"message\":\"导入成功,请再次查询确认。\"}"));
		return null;
	}
	
	private TownForm getTownForm(HSSFRow row,List provinces,List cities,List districts){

		TownForm townForm = new TownForm();
		townForm.commonReset();
		
		int blankCount = 0;
		String value = getCellValue(row, 0);
		if(!StringUtils.isEmpty(value)){
			townForm.setProvinceId(CommonUtils.provinceAbbrToCode(value, provinces));
		}else{
			blankCount++;
		}
		
		value = getCellValue(row, 1);
		if(!StringUtils.isEmpty(value)){
			townForm.setCityId(CommonUtils.cityNameToCode(value, cities));
		}else{
			blankCount++;
		}
		
		value = getCellValue(row, 2);
		if(!StringUtils.isEmpty(value)){
			townForm.setDistrictId(CommonUtils.districtNameToCode(value, districts));
		}else{
			blankCount++;
		}
		
		value = getCellValue(row, 3);
		if(!StringUtils.isEmpty(value)){
			townForm.setAge(value);
		}else{
			blankCount++;
		}
		
		value = getCellValue(row, 4);
		if(!StringUtils.isEmpty(value)){
			Long amount = new Long(1L);
			try {
				amount = new Long(value);
			} catch (Exception e) {
				e.printStackTrace();
			}
			townForm.setAmount(amount);
		}else{
			blankCount++;
		}
		if(blankCount > 4) return null;
		return townForm;
	}
	
	private String getCellValue(HSSFRow row,int cellNum){
		String value = null;
		HSSFCell cell = row.getCell(cellNum);
		if(cell == null) return value;
		HSSFRichTextString rString = cell.getRichStringCellValue();
		if(rString == null) return value;
		value = rString.getString();
		return value;
	}
	
	

	protected ActionForward handleFile(ActionMapping mapping,
			HttpServletRequest request, HttpServletResponse response) {
		renderHtml(response,
				saveWrapper("{\"error\":\"" + errorMessages + "\"}"));
		return null;
	}
}
